package com.jqkb.service;

import android.app.DownloadManager;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.webkit.MimeTypeMap;
import android.widget.Toast;

import com.fasterxml.jackson.databind.JsonNode;
import com.jqkb.TheApplication;
import com.jqkb.service.util.CallBack;
import com.jqkb.service.util.Converter;
import com.jqkb.service.util.SimpleApi;
import com.jqkb.utils.Constant;

import okhttp3.ResponseBody;
import org.apache.commons.lang3.math.NumberUtils;
import retrofit2.Call;

import java.io.File;
import java.io.FilenameFilter;
import java.net.URISyntaxException;

public class UpdateVersionService extends Service {
    private String TAG = UpdateVersionService.class.getSimpleName();

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        checkVersionAndUpdate();
        return START_NOT_STICKY;
    }

    public String getVersionName() {
        String versionCode = "";
        try {
            //获取软件版本号，对应AndroidManifest.xml下android:versionCode
            versionCode = this.getPackageManager().
                    getPackageInfo(this.getPackageName(), 0).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionCode;
    }

    public int getVersionCode() {
        int versionCode = 0;
        try {
            //获取软件版本号，对应AndroidManifest.xml下android:versionCode
            versionCode = this.getPackageManager().
                    getPackageInfo(this.getPackageName(), 0).versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionCode;
    }

    private void checkVersionAndUpdate() {
        final VersionService service = SimpleApi.create(VersionService.class);
        Call<ResponseBody> call = service.checkVersion();
        Converter.convert(Object.class, call, new CallBack<Object>() {
            @Override
            public void onSuccess(Object object, JsonNode data) {
                String localVersionName = getVersionName();
                int localVersionCode = getVersionCode();
                JsonNode path = data.path("data");
                String newVersionName = path.path("version").asText();
                long length = path.path("length").asLong();
                final int newVersionCode = NumberUtils.toInt(newVersionName.replaceAll("\\D", ""));
                // 设置下载文件的保存位置
                File directory = Environment.getExternalStoragePublicDirectory("JQKB");
                directory.mkdirs();
                final File saveFile = new File(directory, "JQKB" + newVersionName + ".apk");

                //除了当前版本其他升级安装包文件都删除
                deletePreviousApkFile(directory, saveFile);

                if (saveFile.length() == length && newVersionCode > localVersionCode) {
                    try {
                        startInstall(saveFile, Uri.fromFile(saveFile).toString());
                    } catch (URISyntaxException e) {
                        e.printStackTrace();
                    }
                    return;
                }
                if (newVersionCode > localVersionCode) {
                    Toast.makeText(UpdateVersionService.this, "发现新版本(" + newVersionName + ")正在更新", Toast.LENGTH_SHORT).show();
                    final String url = path.path("url").asText();
                    try {
                        final DownloadManager downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
                        long versionDownloadId = TheApplication.getSharedPreferences().getLong("versionDownloadId", 0);
                        final DownloadManager.Query query = new DownloadManager.Query();
                        query.setFilterById(versionDownloadId);
                        final Cursor cursor = downloadManager.query(query);
                        boolean end = false;
                        if (cursor.moveToFirst()) {
                            int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
                            String localUri = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
                            if (status == DownloadManager.STATUS_RUNNING
                                    || status == DownloadManager.STATUS_PAUSED
                                    || status == DownloadManager.STATUS_PENDING) {
                                end = true;
                            }
                            if (status == DownloadManager.STATUS_SUCCESSFUL && saveFile.length() == length) {
                                Toast.makeText(UpdateVersionService.this, "已下载新版本(" + newVersionName + ")进行安装", Toast.LENGTH_SHORT).show();
                                startInstall(saveFile, localUri);
                                end = true;
                            }
                        }
                        cursor.close();
                        if (end) {
                            return;
                        }

                        String downloadUrl = TheApplication.getServer() + url;
                        // 创建下载请求
                        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(downloadUrl));
                        /*
                         * 设置在通知栏是否显示下载通知(下载进度), 有 3 个值可选:
                         *    VISIBILITY_VISIBLE:                   下载过程中可见, 下载完后自动消失 (默认)
                         *    VISIBILITY_VISIBLE_NOTIFY_COMPLETED:  下载过程中和下载完成后均可见
                         *    VISIBILITY_HIDDEN:                    始终不显示通知
                         */
                        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
                        // 设置通知的标题和描述
                        request.setTitle("警情快报升级");
                        request.setDescription(String.valueOf(newVersionName));
                        /*
                         * 设置允许使用的网络类型, 可选值:
                         *     NETWORK_MOBILE:      移动网络
                         *     NETWORK_WIFI:        WIFI网络
                         *     NETWORK_BLUETOOTH:   蓝牙网络
                         * 默认为所有网络都允许
                         */
                        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
                        request.setVisibleInDownloadsUi(true);
                        // 添加请求头
                        // request.addRequestHeader("User-Agent", "Chrome Mozilla/5.0");

//                        Uri uri;
//                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//
//                            uri= FileProvider.getUriForFile(UpdateVersionService.this,"com.jqkb.FileProvider",saveFile)
//                        }
//                        else {
//                            uri=  Uri.fromFile(saveFile);
//                        }
//                        request.setDestinationUri(uri);//这个方法无法下载

                        //下载到APK私有目录
                        request.setDestinationInExternalPublicDir("JQKB", "JQKB" + newVersionName + ".apk");

                        /*
                         * 2. 获取下载管理器服务的实例, 添加下载任务
                         */

                        // 将下载请求加入下载队列, 返回一个下载ID
                        final long downloadId = downloadManager.enqueue(request);
                        long previousDownloadId = TheApplication.getSharedPreferences().getLong("versionDownloadId", 0);
                        downloadManager.remove(previousDownloadId);
                        TheApplication.getSharedPreferences().edit().putLong("versionDownloadId", downloadId).commit();

                        final IntentFilter intentFilter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
                        UpdateVersionService.this.registerReceiver(new BroadcastReceiver() {
                            @Override
                            public void onReceive(Context context, Intent intent) {
                                long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
                                if (downloadId == id) {
                                    Toast.makeText(context, "警情快报新版本下载完成", Toast.LENGTH_SHORT).show();
                                    DownloadManager.Query queryComplete = new DownloadManager.Query();
                                    queryComplete.setFilterById(id);
                                    queryComplete.setFilterByStatus(DownloadManager.STATUS_SUCCESSFUL);

                                    Cursor cursorComplete = downloadManager.query(queryComplete);
                                    if (cursorComplete.moveToFirst()) {
                                        try {
                                            String localUri = cursorComplete.getString(cursorComplete.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
//                                            downloadManager.remove(id);
                                            TheApplication.getSharedPreferences().edit().remove(Constant.VERSION_DOWNLOAD_ID).commit();
                                            startInstall(saveFile, localUri);
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        } finally {
                                            context.unregisterReceiver(this);
                                        }
                                    }
                                    cursorComplete.close();


                                }
                            }
                        }, intentFilter);


                        // 如果中途想取消下载, 可以调用remove方法, 根据返回的下载ID取消下载, 取消下载后下载保存的文件将被删除
                        // downloadManager.remove(downloadId);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }


                }


            }

            @Override
            public void onFail(boolean success, int code, String message, JsonNode data) {
                Toast.makeText(UpdateVersionService.this, "失败:" + message, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onNetworkFail(Call<ResponseBody> jsonNode) {
                Toast.makeText(UpdateVersionService.this, "网路连接失败", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onError(Call<ResponseBody> response) {
                Toast.makeText(UpdateVersionService.this, "网路连接失败", Toast.LENGTH_SHORT).show();
            }
        });

    }

    /**
     * 除了当前版本其他升级安装包文件都删除
     */
    private void deletePreviousApkFile(File directory, final File currentApkFile) {
        String[] list = directory.list(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                if (name.startsWith("JQKB") && name.endsWith(".apk")
                        && !name.equals(currentApkFile.getName())
                        )
                    return true;
                else
                    return false;
            }
        });
        for (String s : list) {
            File oldVersionApkFile = new File(directory, s);
            oldVersionApkFile.delete();
        }
    }

    private void startInstall(File apkFile, String localUri) throws URISyntaxException {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        String apkMimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension("apk");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Log.w(TAG, "版本大于 N ，开始使用 fileProvider 进行安装");
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(
                    this
                    , "com.jqkb.FileProvider"
                    , apkFile);
            intent.setDataAndType(contentUri, apkMimeType);
        } else {
            Log.w(TAG, "正常进行安装");
            intent.setDataAndType(Uri.parse(localUri), apkMimeType);
        }
        startActivity(intent);
    }
}
